package com.example.a_java.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.a_java.common.Result;
import com.example.a_java.entity.LoanRepaymentPlan;
import com.example.a_java.service.LoanRepaymentPlanService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 还款计划Controller
 */
@Tag(name = "还款计划管理", description = "还款计划管理相关接口")
@RestController
@RequestMapping("repayment/plan")
@SecurityRequirement(name = "bearer-key")
public class LoanRepaymentPlanController {

    @Autowired
    private LoanRepaymentPlanService repaymentPlanService;

    /**
     * 获取还款计划列表
     */
    @Operation(summary = "获取还款计划列表")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('loan:repayment:list')")
    public Result<Page<LoanRepaymentPlan>> list(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "合同ID") @RequestParam(required = false) Long contractId,
            @Parameter(description = "还款状态") @RequestParam(required = false) Integer repayStatus) {
        
        Page<LoanRepaymentPlan> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<LoanRepaymentPlan> wrapper = new LambdaQueryWrapper<>();
        
        wrapper.eq(contractId != null, LoanRepaymentPlan::getContractId, contractId)
                .eq(repayStatus != null, LoanRepaymentPlan::getRepayStatus, repayStatus)
                .orderByAsc(LoanRepaymentPlan::getTermNo);
        
        repaymentPlanService.page(page, wrapper);
        return Result.success(page);
    }

    /**
     * 获取还款计划详情
     */
    @Operation(summary = "获取还款计划详情")
    @GetMapping("/{planId}")
    @PreAuthorize("hasAuthority('loan:repayment:query')")
    public Result<LoanRepaymentPlan> getInfo(@PathVariable Long planId) {
        return Result.success(repaymentPlanService.getById(planId));
    }

    /**
     * 生成还款计划
     */
    @Operation(summary = "生成还款计划")
    @PostMapping("/generate")
    @PreAuthorize("hasAuthority('loan:repayment:add')")
    public Result<Map<String, Object>> generate(@RequestBody Map<String, Long> params) {
        Long contractId = params.get("contractId");
        if (contractId == null) {
            return Result.fail("合同ID不能为空");
        }
        
        boolean success = repaymentPlanService.generateRepaymentPlan(contractId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        result.put("contractId", contractId);
        
        if (success) {
            // 查询生成的还款计划数量
            LambdaQueryWrapper<LoanRepaymentPlan> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LoanRepaymentPlan::getContractId, contractId);
            long count = repaymentPlanService.count(wrapper);
            result.put("planCount", count);
            result.put("message", "还款计划生成成功");
        } else {
            result.put("message", "还款计划生成失败，请检查合同信息");
        }
        
        return Result.success(result);
    }

    /**
     * 获取合同还款计划
     */
    @Operation(summary = "获取合同还款计划")
    @GetMapping("/contract/{contractId}")
    @PreAuthorize("hasAuthority('loan:repayment:query')")
    public Result<List<LoanRepaymentPlan>> getContractPlans(@PathVariable Long contractId) {
        LambdaQueryWrapper<LoanRepaymentPlan> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LoanRepaymentPlan::getContractId, contractId)
                .orderByAsc(LoanRepaymentPlan::getTermNo);
        
        List<LoanRepaymentPlan> plans = repaymentPlanService.list(wrapper);
        return Result.success(plans);
    }
} 
